import React from 'react';
import PropTypes from 'prop-types';
import routes from './routes';
import {Button, Form, Row, Col, Card, Spin, Table, Popconfirm, Modal} from 'antd';
import {FORM_OPTIONS, TABLE, FIXED_COLUMN_WIDTH} from '../constants';
import Return from '../common/Return';
import * as api from './api';
import FormItem from 'antd/lib/form/FormItem';
import {hasPermissions} from './utils';
import {PERMISSIONS} from './constants';
import {injectIntl} from './intl';
import styles from './style.css';
import SelectPanel from '../common/DealerSelect/SelectPanel';
export class UpdatePanel extends React.PureComponent {
    state = {
        loading: false,
        hasOperat: false,
        validate: false,
        data: {},
        details: [],
        showDealerSelectPanel: false,
    };

    componentDidMount() {
        const id = this.props.id;
        this.setState({loading: true});
        api.getDetail(id)
            .then(res => {
                if(res.ok)
                    this.setState({
                        loading: false,
                        data: res.data,
                        details: res.data.dealers
                    });
                else
                    this.setState({loading: false});
            });
    }
    componentWillUnmount() {
        this.isunmount = true;
    }
    handleFilterChange = (value, name) => {
        const data = Object.assign({}, this.state.data, {
            [name]: value
        });
        this.setState({
            data,
            hasOperat: true
        });
    }
    onClickReturnBtn = () => {
        this.props.onCancel();
    }
    onSubmit = () => {
        this.setState({loading: true});
        this.props.onSubmit(this.state.data, this.state.details).then(res => {
            if(res.success)
                this.props.successReturn();
            if(!this.isunmount)
                this.setState({loading: false});
        });
    }
    onClickAddBtn = () => {
        this.setState({showDealerSelectPanel: true});
    }
    onDeleteAddedItem = e => {
        const addedItemId = e.target.dataset.id;
        const tmp = this.state.details.filter(d => d.id !== addedItemId);
        this.setState({
            details: [...tmp],
            hasOperat: true
        });
    }
    onDeleteAll = () => {
        this.setState({
            details: [],
            hasOperat: true
        });
    }
    onClickSearchDealerBtn = () => {
        this.setState({showDealerSelectPanel: true});
    }
    onCloseDealerSelectPanel= () => {
        this.setState({showDealerSelectPanel: false});
    }
    onSelectDealer = record => {
        const addedItems = this.state.details || [];
        const index = addedItems.findIndex(v => v.id === record.id);
        if(index === -1)
            addedItems.push({
                id: record.id,
                code: record.code,
                name: record.name
            });
        this.setState({
            details: [...addedItems],
            showDealerSelectPanel: false,
            hasOperat: true
        });
    }
    render() {
        const {data, details} = this.state;
        const {formatMessage} = this.props.intl;
        const {pagePermission} = this.props;

        const validateName = !data.name && this.state.validate ? 'error' : null;
        const submitable = hasPermissions(PERMISSIONS.add, pagePermission);
        const colums = [{
            title: formatMessage({
                id: 'newPanel.column.code',
                defaultMessage: '总代编号'
            }),
            dataIndex: 'code',
        }, {
            title: formatMessage({
                id: 'newPanel.column.name',
                defaultMessage: '总代名称'
            }),
            dataIndex: 'name',
        }, {
            title: details && details.length > 0
                ? (
                    <Popconfirm placement="topRight" title={formatMessage({
                        id: 'newPanel.column.allDelete',
                        defaultMessage: '是否确认全部删除？'
                    })} onConfirm={this.onDeleteAll} >
                        <a>{formatMessage({
                            id: 'newPanel.column.empty',
                            defaultMessage: '清空'
                        })}</a>
                    </Popconfirm>
                )
                : <a>{formatMessage({
                    id: 'newPanel.column.empty',
                    defaultMessage: '清空'
                })}</a>,
            dataIndex: 'id',
            fixed: 'right',
            width: FIXED_COLUMN_WIDTH,
            render: text => <a data-id={text} onClick={this.onDeleteAddedItem}>{formatMessage({
                id: 'newPanel.column.delete',
                defaultMessage: '删除'
            })}</a>
        }];
        return (
            <div className="form-standard">
                <Spin spinning={this.state.loading}>
                    <Form>
                        <Card {...FORM_OPTIONS.col} title={formatMessage({
                            id: 'editPanel.card.title',
                            defaultMessage: '基本信息'
                        })}>
                            <Row>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.operation.code',
                                        defaultMessage: '编号'
                                    })}{...FORM_OPTIONS.item}
                                    validateStatus={validateName}
                                    required>
                                        {data.code}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.operation.name',
                                        defaultMessage: '名称'
                                    })} {...FORM_OPTIONS.item}
                                    validateStatus={validateName}
                                    required>
                                        {data.name}
                                    </FormItem>
                                </Col>
                            </Row>
                            <Row>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.operation.branchCode',
                                        defaultMessage: '营销分公司编号'
                                    })} {...FORM_OPTIONS.item}>
                                        {data.branchCode}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.operation.branchName',
                                        defaultMessage: '营销分公司名称'
                                    })} {...FORM_OPTIONS.item}>
                                        {data.branchName}
                                    </FormItem>
                                </Col>
                            </Row>
                        </Card>
                        <Card
                            title={formatMessage({
                                id: 'editPanel.card.title.detail',
                                defaultMessage: '关系清单'
                            })}
                            extra={<Button
                                size="small"
                                onClick={this.onClickAddBtn}>
                                {formatMessage({
                                    id: 'newPanel.operation.newDetail',
                                    defaultMessage: '选择总代子公司'
                                })}
                            </Button>}>
                            <Table
                                className="white-space-nowrap"
                                rowKey="id"
                                columns={colums}
                                pagination={false}
                                dataSource={details}
                                {...TABLE} />
                        </Card>
                        <Card type="inner">
                            <Row>
                                <Col disabled={!submitable} className="col-align-right">
                                    <Button key="submit" loading={this.state.loading}
                                        onClick={this.onSubmit} type="primary">{formatMessage({
                                            id: 'editPanel.submit',
                                            defaultMessage: '保存'
                                        })}</Button>
                                </Col>
                            </Row>
                        </Card>
                    </Form>
                </Spin>
                <Modal
                    title={formatMessage({
                        id: 'dealer.dealers.modal.item.title',
                        defaultMessage: '总代子公司查询'
                    })}
                    width="80%"
                    maskClosable={false}
                    footer={null}
                    wrapClassName={styles.dataSelectModal}
                    destroyOnClose={true}
                    visible={this.state.showDealerSelectPanel}
                    onCancel={this.onCloseDealerSelectPanel}>
                    <Row gutter={8}>
                        <Col md={16} xl={16} xxl={18}><Card>
                            <SelectPanel
                                onSelect={this.onSelectDealer}
                                getDealers={this.props.getDealers}
                                getRegions={this.props.getRegions}
                                getMarketDepartments={this.props.getMarketDepartments} />
                        </Card></Col>
                    </Row>
                </Modal>
                <div className="page-toolbar">
                    <Return
                        onConfirm={this.onClickReturnBtn}
                        disabled={this.state.loading}
                        showWarning={this.state.hasOperat} />
                </div>
            </div>
        );
    }
}

const EMPTY_OBJECT = {};

UpdatePanel.defaultProps = {
    allowClear: true,
    searchOnFocus: true,
    getDealer: api.getDealers,
    getRegions: api.getRegions,
    getMarketDepartments: api.getMarketDepartments,
    conditions: EMPTY_OBJECT
};

UpdatePanel.propTypes = {
    successReturn: PropTypes.func.isRequired,
    onCancel: PropTypes.func.isRequired,
    onSubmit: PropTypes.func.isRequired,
    history: PropTypes.object,
    intl: PropTypes.object,
    pagePermission: PropTypes.array
};
import {connect} from 'react-redux';
import {
    onSubmit,
    tableSearch,
} from './actions';
import {selectorFactory} from 'Shared/utils/immutableToJsSelectorFactory';
const getPagePermission = selectorFactory(['page', 'domainData', 'permissions', 'data']);

const mapStateToProps = state => ({
    pagePermission: getPagePermission(state),
});

const mapDispatchToProps = (dispatch, props) => ({
    onSubmit: (data, details) => dispatch(onSubmit(props.id, details)),
    onCancel: () => props.history.push(routes.query.url()),
    successReturn: () => {
        dispatch(tableSearch());
        props.history.push(routes.query.url());
    },
});

export default connect(mapStateToProps, mapDispatchToProps)(injectIntl(UpdatePanel));
